﻿using ServiceStack.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace YiYiTong.Rocket.Helper.Redis
{
    /// <summary>
    /// redis订阅发布
    /// </summary>
    public class RedisSubscriptHelper
    {
        /// <summary>
        /// 订阅
        /// </summary>
        public static void Subscription(IRedisClient consumer, string msgchannel)
        {

            //创建订阅
            ServiceStack.Redis.IRedisSubscription subscription = consumer.CreateSubscription();

            //接收消息处理Action
            subscription.OnMessage = (channel, msg) =>
            {
                Console.WriteLine("频道【" + channel + "】订阅客户端接收消息：" + ":" + msg + "         [" + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + "]");
                Console.WriteLine("订阅数：" + subscription.SubscriptionCount);
                Console.WriteLine("___________________________________________________________________");

            };

            //订阅事件处理
            subscription.OnSubscribe = (channel) =>
            {
                Console.WriteLine("订阅客户端：开始订阅" + channel);
            };

            //取消订阅事件处理
            subscription.OnUnSubscribe = (a) => { Console.WriteLine("订阅客户端：取消订阅"); };

            ////模拟：发送100条消息给服务
            //Task.Run(() =>
            //{
            //    using (ServiceStack.Redis.IRedisClient publisher = new ServiceStack.Redis.RedisClient("172.16.16.65", 6379))
            //    {
            //        for (int i = 1; i <= 100; i++)
            //        {
            //            publisher.PublishMessage("channel-1", string.Format("这是我发送的第{0}消息!", i));
            //            System.Threading.Thread.Sleep(200);
            //        }
            //    }
            //    subscription.UnSubscribeFromAllChannels();
            //});

            //订阅频道
            subscription.SubscribeToChannels(msgchannel);
        }

    }
}
